package com.tencreat.service.mall.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.domain.entity.SysDictType;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.OrderStatus;
import com.tencreat.common.enums.UserType;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.MallAddress;
import com.tencreat.domain.mall.MallMessageInform;
import com.tencreat.domain.mall.MallOrderGoods;
import com.tencreat.domain.mall.dto.MallMessageInformApiOrderDTO;
import com.tencreat.domain.mall.dto.MallMessageInformPushDTO;
import com.tencreat.domain.mall.vo.MallMessageInformApiOrderVO;
import com.tencreat.domain.mall.vo.MallMessageInformApiSystemVO;
import com.tencreat.mapper.account.MallUserMapper;
import com.tencreat.mapper.mall.MallMessageInformMapper;
import com.tencreat.mapper.system.SysDictTypeMapper;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IMallAddressService;
import com.tencreat.service.mall.IMallMessageInformService;
import com.tencreat.service.mall.IMallOrderGoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 消息通知Service业务层处理
 *
 * @author tencreat
 * @date 2021-11-25
 */
@Service
@RequiredArgsConstructor
public class MallMessageInformServiceImpl extends ServiceImpl<MallMessageInformMapper, MallMessageInform> implements IMallMessageInformService {

    private final MallUserMapper userMapper;
    private final SysDictTypeMapper dictTypeMapper;
    private final IMallOrderGoodsService mallOrderService;
    private final IMallAddressService mallAddressService;

    /**
     * 查询消息通知
     *
     * @param id 消息通知ID
     * @return 消息通知
     */
    @Override
    public MallMessageInform selectMallMessageInformById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询消息通知列表
     *
     * @param mallMessageInform 消息通知
     * @return 消息通知
     */
    @Override
    public List<MallMessageInform> selectMallMessageInformList(MallMessageInform mallMessageInform) {
        return baseMapper.selectList(Wrappers.query(mallMessageInform));
    }

    /**
     * 新增消息通知
     *
     * @param mallMessageInform 消息通知
     * @return 结果
     */
    @Override
    public int insertMallMessageInform(MallMessageInform mallMessageInform) {
        mallMessageInform.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(mallMessageInform);
    }

    /**
     * 修改消息通知
     *
     * @param mallMessageInform 消息通知
     * @return 结果
     */
    @Override
    public int updateMallMessageInform(MallMessageInform mallMessageInform) {
        mallMessageInform.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(mallMessageInform);
    }

    /**
     * 批量删除消息通知
     *
     * @param ids 需要删除的消息通知ID
     * @return 结果
     */
    @Override
    public int deleteMallMessageInformByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除消息通知信息
     *
     * @param id 消息通知ID
     * @return 结果
     */
    @Override
    public int deleteMallMessageInformById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    public void push(MallMessageInformPushDTO vo) {
        // 获取消息用户人群
        List<MallUser> users = new ArrayList<>();
        // 全部用户
        IMallUserService userService = SpringUtil.getBean(IMallUserService.class);
        if (vo.getTarget() == 1) {
            users = userService.lambdaQuery().select(MallUser::getUuid).list();
        }
        /*else if (vo.getTarget() == 0) {
            users = userService.lambdaQuery().eq(MallUser::getUserLevel, UserType.INTERMEDIATE_MEMBER).select(MallUser::getUuid).list();
        }*/
        // 指定用户
        else if (vo.getTarget() == 2) {
            if (StringUtils.isBlank(vo.getUserList())) {
                throw new CustomException("指定用户不能为空");
            }
            String[] split = vo.getUserList().split(",");
            // 拼接指定用户
            users = userMapper.selectList(new LambdaQueryWrapper<MallUser>().select(MallUser::getUuid).in(MallUser::getMobile, Arrays.asList(split)));
            if (users.size() == 0) {
                throw new CustomException("指定用户找不到");
            }
        }

        // 系统消息
        users.parallelStream().forEach(item -> {
            MallMessageInform messageInform = new MallMessageInform();
            messageInform.setTitle(vo.getTitle());
            messageInform.setContent(vo.getContent());
            messageInform.setType(1);
            messageInform.setUnread(0);
            messageInform.setUserId(item.getUuid());
            messageInform.setCreateTime(LocalDateTime.now());
            baseMapper.insert(messageInform);
        });
        // 短信消息
//        else {
//
//        }
    }

    @Override
    public Integer unread(Integer type) {
        Long userId = SecurityUtils.getLoginUser().getAccountLogin().getUuid();
        int count = 0;
        if (type == null) {
            count = count(new LambdaQueryWrapper<MallMessageInform>()
                    .eq(MallMessageInform::getUserId, userId).eq(MallMessageInform::getUnread, 0));
        } else if (type == 0) {
            count = count(new LambdaQueryWrapper<MallMessageInform>()
                    .eq(MallMessageInform::getUserId, userId)
                    .eq(MallMessageInform::getUnread, 0)
                    .eq(MallMessageInform::getType, type));
        } else if (type == 1) {
            count = count(new LambdaQueryWrapper<MallMessageInform>()
                    .eq(MallMessageInform::getUserId, userId)
                    .eq(MallMessageInform::getUnread, 0)
                    .and(wrapper -> {
                        wrapper.eq(MallMessageInform::getType, 1)
                                .or()
                                .eq(MallMessageInform::getType, 2);
                    }));
        }
        return count;
    }

    @Override
    public void clearUnread(Integer type) {
        Long userId = SecurityUtils.getLoginUser().getAccountLogin().getUuid();
        if (type == 0) {
            update(new LambdaUpdateWrapper<MallMessageInform>()
                    .eq(MallMessageInform::getUserId, userId)
                    .eq(MallMessageInform::getType, 0)
                    .set(MallMessageInform::getUnread, 1));
        } else if (type == 1) {
            update(new LambdaUpdateWrapper<MallMessageInform>()
                    .eq(MallMessageInform::getUserId, userId)
                    .and(wrapper -> {
                        wrapper.eq(MallMessageInform::getType, 1)
                                .or()
                                .eq(MallMessageInform::getType, 2);
                    })
                    .set(MallMessageInform::getUnread, 1));
        }
    }

    @Override
    public List<MallMessageInformApiSystemVO> system() {
        Long userId = SecurityUtils.getLoginUser().getAccountLogin().getUuid();
        return baseMapper.system(userId);
    }

    @Override
    public List<MallMessageInformApiOrderVO> order(Page<MallMessageInformApiOrderDTO> page) {
        Long uuid = SecurityUtils.getLoginUser().getAccountLogin().getUuid();
        return baseMapper.order(uuid, page);
    }

    @Override
    public void addOrderMessage(String title, Long orderId, Long userId) {
        MallMessageInform messageInform = new MallMessageInform();
        messageInform.setUserId(userId);
        messageInform.setTitle(title);
        messageInform.setType(0);
        messageInform.setUnread(0);
        messageInform.setBusinessId(orderId);
        if (title.equals("请您核对订单信息")) {
            // 未确认
            messageInform.setConfirm(0);
            messageInform.setMessageType(1);
        }
        insertMallMessageInform(messageInform);
    }

    @Override
    public void addSystemMessage(String title, String content, Long userId) {
        MallMessageInform messageInform = new MallMessageInform();
        messageInform.setUserId(userId);
        messageInform.setTitle(title);
        messageInform.setContent(content);
        messageInform.setType(1);
        messageInform.setUnread(0);
        messageInform.setDelFlag("0");
        insertMallMessageInform(messageInform);
    }

    @Override
    public void addSystemMessage(String title, String content, String reply, Long userId) {
        MallMessageInform messageInform = new MallMessageInform();
        messageInform.setUserId(userId);
        messageInform.setTitle(title);
        messageInform.setContent(content);
        messageInform.setReply(reply);
        messageInform.setType(1);
        messageInform.setUnread(0);
        insertMallMessageInform(messageInform);
    }

    @Override
    public void addRegisterSuccess(Long uuid) {
        MallMessageInform messageInform = new MallMessageInform();
        messageInform.setUserId(uuid);
        messageInform.setTitle("注册成功");
        messageInform.setContent("注册成功");
        messageInform.setReply(null);
        messageInform.setType(1);
        messageInform.setUnread(0);
        // 查询系统注册消息
        SysDictType dictType = dictTypeMapper.selectDictTypeByType("welcome_to_register");
        if (dictType != null) {
            messageInform.setContent(dictType.getRemark());
        }
    }

    @Override
    public void updateOrderAddress(Long id, Long addressId) {
        // 查询消息
        MallMessageInform one = lambdaQuery().eq(MallMessageInform::getId, id).one();
        if (one == null) {
            throw new CustomException("订单信息有误");
        }
        if (one.getConfirm() != 0) {
            throw new CustomException("该订单已被确认过");
        }
        // 查询订单信息
        MallOrderGoods mallOrder = mallOrderService.getById(one.getBusinessId());
        if (mallOrder == null) {
            throw new CustomException("订单信息有误");
        }
        if (mallOrder.getOrderStatus().getValue() != OrderStatus.WAIT_DELIVER.getValue()) {
            throw new CustomException("该订单已发货，不能修改地址");
        }
        if (addressId != null) {
            MallAddress mallAddress = mallAddressService.getById(addressId);
            mallOrder.setConsignee(mallAddress.getName());
            mallOrder.setMobile(mallAddress.getTel());
            mallOrder.setAddress(mallAddress.getProvinceName() + mallAddress.getCityName() + mallAddress.getCountyName()
                    + mallAddress.getAddressDetail());
        }
        lambdaUpdate().eq(MallMessageInform::getId, id)
                .set(MallMessageInform::getConfirm, 1)
                .set(MallMessageInform::getTitle, "订单信息修改成功")
                .update();
        // 修改订单信息
        mallOrderService.lambdaUpdate().eq(MallOrderGoods::getId, mallOrder.getId())
                .set(MallOrderGoods::getConsignee, mallOrder.getConsignee())
                .set(MallOrderGoods::getMobile, mallOrder.getMobile())
                .set(MallOrderGoods::getAddress, mallOrder.getAddress())
                .set(MallOrderGoods::getReceiptAddressId, addressId)
                .update();
    }
}
